package org.jwd.storage.dao;

import org.apache.ibatis.annotations.Param;
import org.jwd.core.exception.RollBackWithNoIdException;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @author vizz
 * @since 2022/5/19 20:35
 */
public class RollbackSqlProvider {

    public String rollInsertProvider(HashMap<String, String> map, @Param("tableName") String tableName) {
        String id = map.get("id");
        if (StringUtils.isEmpty(id)) {
            throw new RollBackWithNoIdException("id不能为空！");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ${tableName} SET ");
        sql.append("deleted=1 ");
        sql.append("WHERE id=" + id);
        return sql.toString();
    }

    public String rollDeleteProvider(HashMap<String, String> map, @Param("tableName") String tableName) {
        String id = map.get("id");
        if (StringUtils.isEmpty(id)) {
            throw new RollBackWithNoIdException("id不能为空！");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ${tableName} SET ");
        sql.append("deleted=0 ");
        sql.append("WHERE id=" + id);
        return sql.toString();
    }

    public String rollUpdateProvider(HashMap<String, String> map, @Param("tableName") String tableName) {
        String id = map.get("id");
        if (StringUtils.isEmpty(id)) {
            throw new RollBackWithNoIdException("id不能为空！");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ${tableName} SET ");
        map.forEach((k, v) -> {
            sql.append(String.format("'%s'='%s',", k, v));
        });
        sql.replace(sql.length() - 1, sql.length(), "");
        sql.append("WHERE id=" + id);
        return sql.toString();
    }


}
